<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-07
 * Time: 21:49
 */

namespace App\Services\Front;


use App\Models\Cart;
use App\Models\Commodity;
use App\Models\CommoditySku;
use App\Models\Order;
use App\Models\OrderDetail;

class OrderService
{
    /**
     * 组装数据
     * @param $data
     * @return mixed
     */
    public function createOrderStep1($data)
    {
        foreach ($data['commodityList'] as $value){
            $result['commodityId'][] = $value['commodityId'];
            $result['cartId'][] = !empty($value['cartId']) ? $value['cartId'] : '';
            $result['amount'][] = !empty($value['amounts']) ? $value['amounts'] : '';
        }
        return $result;
    }

    public function createOrderStep2($data)
    {

        $totalPrice = 0;
        $goods_freight = 0;
        $commodity = $this->getGoodsBySkuId($data['cartId'],$data['commodityId'],$data['amount']);
        //获取商品信息 计算出总金额
        if(!empty($commodity)){
            foreach ($commodity as $key=>$value){
                    $total = ($value['nowPrice'] * $value['amounts']);//单价
                    $totalPrice += $total;//总金额
            }
        }else{
            throw new \Exception("数据不正确");
        }
        $commodityList['commodity'] = $commodity;
        $commodityList['totalNum'] = $totalPrice; //总金额
        $commodityList['commidityFreight'] = 0; // 运费
        $commodityList['totalFreightNum'] = ($totalPrice + $goods_freight)*100; //加上运费后的金额
        return $commodityList;
    }


    //提交第三步 生成订单信息 并保存进入订单表中
    public function createOrderStep3($data, $address, $userId)
    {
        $order['orderNo'] = getOrderSn("S");
        $order['userId'] = $userId;
        $order['createTime'] = date("Y-m-d H:i:s");
        $order['totalPrice'] = $data['totalFreightNum'];//商品总价格
        $order['totalFee'] = $data['totalFreightNum'];//订单总支付价格
        $order['postage'] = $data['commidityFreight'];//邮费
        $order['orderStatus'] = "NONPAYMENT";
        $order['reciverName'] = $address['reciverName'];
        $order['province'] = $address['province'];
        $order['city'] =  $address['city'];
        $order['district'] = $address['district'];
        $order['zipCode'] = @$address['zipCode'];

        $order['detailAddress'] = $address['detailAddress'];
        $order['phoneNumber'] = $address['phoneNumber'];
        $order['userRemark'] = " ";


        $status = Order::create($order);
        if(!$status){
            throw new \Exception('保存订单失败！');
        }
        $orderGoods = [];

        foreach ($data['commodity'] as $key => $value){
            $orderGoods[$key]['orderNo'] = $order['orderNo'];
            $orderGoods[$key]['skuId'] = 0;
            $orderGoods[$key]['commodityName'] = $value['caption'];
            $orderGoods[$key]['commodityPrice'] = $value['originalPrice']*100;
            $orderGoods[$key]['commodityIcon'] =  $value['bgPicture'];
            $orderGoods[$key]['descPictures'] = $value['content'];
            $orderGoods[$key]['amounts'] = $value['amounts'];
            $orderGoods[$key]['commodityId'] = $value['commodityId'];
            $orderGoods[$key]['type'] = $value['type'];
            $orderGoods[$key]['discount'] = $value['nowPrice']*100;
            $orderGoods[$key]['totalPrice'] = ($value['nowPrice']) * ($value['amounts']) * 100;
        }
        $status = OrderDetail::insert($orderGoods);
        if(!$status){
            throw new \Exception('保存订单失败！');
        }
        $orderGoods['totalFee'] = $order['totalFee'];
        return $orderGoods;
    }


    public function createOrderStep4($commodity,$cartId)
    {

//        $this->decrementStorage($commodity);
        $this->incrementSale($commodity);
        if($cartId[0]){
            $this->deleteCart($cartId);
        }
        return true;
    }

    /**
     * 减去商品库存
     * @param $commodity
     * @return bool
     * @throws \Exception
     */
    private function decrementStorage($commodity)
    {

        foreach ($commodity as $value){

            $status = CommoditySku::where('skuId',$value->skuId)->decrement('stock',intval($value->amounts));
            if(!$status){
                throw new \Exception("减去库存失败");
            }
        }
        return true;
    }

    /**
     * 增加销量
     * @param $commodity
     * @return bool
     * @throws \Exception
     */
    private function incrementSale($commodity)
    {
        foreach ($commodity as $value){

            $status = Commodity::where('commodityId',$value['commodityId'])->increment('realSaleCount',intval($value['amounts']));

            if(!$status){
                throw new \Exception("增加销量失败");
            }
        }
        return true;

    }

    /**
     *删除购物车
     * @param $cartId
     * @return bool
     * @throws \Exception
     */
    private function deleteCart($cartId)
    {
        if(empty($cartId)){
            return true;
        }
        $status = Cart::whereIn('cartId',$cartId)->delete();
        if(!$status){
            throw new \Exception("删除购物车失败");
        }
        return true;
    }

    /**
     * 获取商品详情
     * @param $skuId
     * @return \Illuminate\Support\Collection
     * @throws \Exception
     */
    private function getGoodsBySkuId($cartId,$commodityId,$goodsNum)
    {
        if($cartId[0]){//购物车购买
            $commodity = Commodity::select()
                ->from((new Commodity())->getTable().' as t1')
                ->join((new Cart())->getTable().' as t2','t1.commodityId','=','t2.commodityId')
                ->whereIn('cartId',$cartId)
                ->get();
        }else{
            $commodity = Commodity::select()
                ->where('commodityId',$commodityId)
                ->where('saleStatus',1)
                ->get();
            $commodity[0]['amounts'] = $goodsNum[0];
        }

        if(!empty($commodity)){
            return $commodity;
        } else {
            throw new \Exception('商品已下架！');
        }
    }


    public function getOrderCommodityDetail($orderNo)
    {
        $data['goods_detail'] = [];
        $orderDetail = OrderDetail::select("*")->where('orderNo',$orderNo)->get()->toArray();
        for($i = 0 ; $i < count($orderDetail); $i ++)
        {
            $data['goods_detail'][$i]['goods_id'] =  $orderDetail[$i]['commodityId'];
            $data['goods_detail'][$i]['quantity'] =  $orderDetail[$i]['amounts'];
            $data['goods_detail'][$i]['price'] =  $orderDetail[$i]['discount'];
        }
        return json_encode($data);
    }
}